using Dilon.Core;
using Dilon.Core.Service;
using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Yitter.IdGenerator;

namespace Dilon.Web.Core
{
    [AppStartup(9)]
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            #region 配置sqlsuagr
            List<ConnectionConfig> connectConfigList = new List<ConnectionConfig>();
            connectConfigList.Add(new ConnectionConfig
            {
                ConnectionString = $"{App.Configuration["ConnectionStrings:DefaultConnection"]}",
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                ConfigId = "0"
            });
            //connectConfigList.Add(new ConnectionConfig
            //{
            //    ConnectionString = $"{App.Configuration["ConnectionStrings:MultiTenantConnection"]}",
            //    DbType = DbType.SqlServer,
            //    IsAutoCloseConnection = true,
            //    InitKeyType = InitKeyType.Attribute,
            //    ConfigId = "1"
            //});

            services.AddSqlSugar(connectConfigList.ToArray()
                , db =>
                {
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                    };
                    //配置多租户全局过滤器
                    db.QueryFilter.Add(new TableFilterItem<SysUser>(it => it.TenantId == long.Parse(GetTenantId().ToString())));
                    db.QueryFilter.Add(new TableFilterItem<SysOrg>(it => it.TenantId == long.Parse(GetTenantId().ToString())));
                    db.QueryFilter.Add(new TableFilterItem<SysPos>(it => it.TenantId == long.Parse(GetTenantId().ToString())));
                    db.QueryFilter.Add(new TableFilterItem<SysRole>(it => it.TenantId == long.Parse(GetTenantId().ToString())));
                });
            #endregion


            services.AddJwt<JwtHandler>(enableGlobalAuthorize:true);

            services.AddCorsAccessor();

            services.AddRemoteRequest();

            services.AddConfigurableOptions<CacheOptions>();

            services.AddControllersWithViews()
                    .AddMvcFilter<RequestActionFilter>()
                    .AddInjectWithUnifyResult<XnRestfulResultProvider>()
                    .AddJsonOptions(options =>
                    {
                        //options.JsonSerializerOptions.DefaultBufferSize = 10_0000;//返回较大数据数据序列化时会截断，原因：默认缓冲区大小（以字节为单位）为16384。
                        options.JsonSerializerOptions.Converters.AddDateFormatString("yyyy-MM-dd HH:mm:ss");
                        //options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // 忽略循环引用 仅.NET 6支持
                    });

            services.AddViewEngine();

            // 设置雪花id的workerId，确保每个实例workerId都应不同
            var workerId = ushort.Parse(App.Configuration["SnowId:WorkerId"] ?? "1");
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions { WorkerId = workerId });

            // 开启自启动定时任务
            App.GetService<ISysTimerService>().StartTimerJob();

            services.AddSimpleEventBus();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            // 添加状态码拦截中间件
            app.UseUnifyResultStatusCodes();

            app.UseHttpsRedirection(); // 强制https
            app.UseStaticFiles();

            // Serilog请求日志中间件---必须在 UseStaticFiles 和 UseRouting 之间
            app.UseSerilogRequestLogging();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

        private object GetTenantId()
        {
            if (App.User == null) return null;
            return App.User.FindFirst(ClaimConst.TENANT_ID)?.Value;
        }
    }
}